<template>
  <p>{{ msg }}</p>
  <!-- <p>{{ data.counter }}</p>
  <p>{{ data.doubleCounter }}</p> -->
  <p>{{ counter }}</p>
  <p>{{ doubleCounter }}</p>
  <p ref="desc"></p>
</template>

<script>
import {
  computed,
  onUnmounted,
  reactive,
  onMounted,
  ref,
  toRefs,
  watch,
} from "vue";
export default {
  setup() {
    // counter 相关
    // const data = reactive({
    //   counter: 1,
    //   doubleCounter: computed(() => data.counter * 2),
    // });

    // let timer;
    // onMounted(() => {
    //   timer = setInterval(() => {
    //     data.counter++;
    //   }, 1000);
    // });
    // onUnmounted(() => {
    //   clearInterval(timer);
    // });

    // const data = useCounter();
    // 使用 toRefs(data) 解构使之响应式
    const { counter, doubleCounter } = useCounter();

    // 单值响应式
    const msg = ref("Composition API");

    // 使用元素的引用
    const desc = ref(null);
    // 监听器
    watch(counter, (val, oldVal) => {
      const p = desc.value;
      p.textContent = `counter change from ${oldVal} to ${val}`;
    });

    return { counter, doubleCounter, msg, desc };
  },
};

function useCounter() {
  const data = reactive({
    counter: 1,
    doubleCounter: computed(() => data.counter * 2),
  });

  let timer;
  onMounted(() => {
    timer = setInterval(() => {
      data.counter++;
    }, 1000);
  });
  onUnmounted(() => {
    clearInterval(timer);
  });

  // return data;
  return toRefs(data);
}
</script>
